package com.newCar;

import com.table.CarTableController2;
import Validator.Validator;
import barecodes.PassesIdCoder;
import com.appclient.ControlledScreen;
import com.appclient.DaoInstanceEnum;
import com.appclient.ScreensController;
import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.Model.CarsModel;
import com.carpark.ejb.Model.ClientsModel;
import com.carpark.ejb.Model.ParkingpassesModel;
import com.carpark.ejb.Model.ParkingspacesModel;
import com.carpark.ejb.Model.PassesrecordsModel;
import com.entries.EntryController;
import com.table.ParkingPassesController;
import com.wizardOther.OtherControlledScreen;
import com.wizardOther.OtherScreensController;
import com.wizardOther.OtherScreensFramework;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import com.wizardOther.Items.ValidationForm;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.layout.GridPane;
import popup.PopupController;
import popup.ScanPopupController;

/**
 *
 * @author Vi
 */
public class NewCarController extends ValidationForm implements Initializable, ControlledScreen {
    
    private ScreensController myController;
    @FXML
    private Button addCar;
    @FXML
    private Button choose;
    @FXML
    private Button scan;
    @FXML
    private Button cancel;
    @FXML
    private TextField plate;
    @FXML
    private TextField make;
    @FXML
    private TextField model;
    @FXML
    private ComboBox carType;
    @FXML
    private TextArea comment;
    @FXML
    private Label labelPlate;
    @FXML
    private Label labelMake;
    @FXML
    private Label labelModel;
    @FXML
    private Label labelCarType;
    @FXML
    private Label labelComment;
    
    @FXML
    private Label idField;
    @FXML
    private Label stField;
    @FXML
    private Label exField;
    @FXML
    private Label spField;
    @FXML
    private Label taField;
    @FXML
    private Label caField;
    
    @FXML
    private GridPane PassesGrid;
    private Integer selectedPass;
    private ParkingpassesModel pass;
    private CarsModel oldCar;
    private ParkingspacesModel space;
    private ParkingPassesController controllerPass;
    private ClientsModel client;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        inputs.clear();
        inputs.add(plate);
        inputs.add(make);
        inputs.add(model);
        inputs.add(carType);
        inputs.add(comment);
        
        labels.clear();
        labels.add(labelPlate);
        labels.add(labelMake);
        labels.add(labelModel);
        labels.add(labelCarType);
        labels.add(labelComment);
        
        labels.add(idField);
        labels.add(stField);
        labels.add(exField);
        labels.add(spField);
        labels.add(taField);
        labels.add(caField);
        
        PassesGrid.setVisible(false);
        
    }
    
    private void clearForm() {
        this.selectedPass = null;
        this.plate.setText("");
        this.make.setText("");
        this.model.setText("");
        this.carType.setValue("Wybierz typ pojazdu");
        this.comment.setText("");
        makeList(5);
        setWrongTextFields(correctField);
    }
    
    @FXML
    private void handleButtonAction(ActionEvent event) {
        if (event.getSource() == addCar) {
            
            addToDB();
        }
        if (event.getSource() == scan) {
            validateForm();
            createScanPopup();
        }
        if (event.getSource() == choose) {
            validateForm();
            showPassTableDialog();
            
            selectedPass = controllerPass.getSelectedPass();
            
            if (this.selectedPass != null) {
                loadData(selectedPass);
            }
        }
        if (event.getSource() == cancel) {
            clearForm();
        }
        
    }
    
    private void loadData(Integer selectedPass) {
        ParkingpassesModel pass = DaoInstanceEnum.INSTANCE.getDao().getParkingPassById(selectedPass);
        //    System.out.println(car.toString());
        if (pass != null) {
            List<PassesrecordsModel> records = new ArrayList<>(pass.getPassesrecordsModelCollection());
            if (!records.isEmpty()) {
                client = records.get(0).getClientId();
                this.pass = pass;
                this.space = pass.getNumberId();
                this.oldCar = pass.getCarId();
                enablePassesGrid();
            }
            
        }
    }
    
    private void validateForm() {
    if(isNotNull(true)){
            makeList(5);
            takeDateFromForm();
            setWrongTextFields(correctField);
            
            printValidator(correctField);
            if (isCorrect(correctField)) {
                
                List<Boolean> goodRecord = Validator.checkCarCheckList(getCar());
                setWrongTextFields(goodRecord);
                
            }
    }
    
       
    }
    
    private boolean isNotNull(Boolean throwPopup) {
        boolean result = false;
        if (this.plate.getText() != null
                && this.make.getText() != null
                && this.model.getText() != null
                && this.carType.getValue() != null) {
            result = true;
        }
        else if(throwPopup){
        createPopup("Uzupełnij wszystkie dane!");
    }
        return result;
    }
    
    private void takeDateFromForm() {
        
        checkString(this.plate.getText(), 0);
        checkString(this.make.getText(), 1);
        checkString(this.model.getText(), 2);
        checkString(renameCarType(this.carType.getValue().toString()), 3);
        checkComments(this.comment.getText(), 4);
        
    }
    
    @FXML
    private void goToMain(java.awt.event.ActionEvent event) {
        myController.setScreen(OtherScreensFramework.OTHER_BUTTONS_PANEL);
    }
    
    private CarsModel getCar() {
        String numberPlate = this.plate.getText();
        String makeText = this.make.getText();
        String modelText = this.model.getText();
        String carTypeText = renameCarType(this.carType.getValue().toString());
        String commentsText = this.comment.getText();
        CarsModel car = new CarsModel(numberPlate, makeText, modelText, carTypeText);
        car.setComments(commentsText);
        //  System.out.println("Plate:" + car.getNumberPlate() + ", carType" + car.getCarType() + ", make" + car.getMake() + ", model " + car.getModel() + "comment: " + car.getComments());

        return car;
    }
    
    @Override
    public void setScreenParent(ScreensController screenParent) {
        myController = screenParent;
    }
    
    private void createScanPopup() {
        if(isNotNull(false)){
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("scanPopup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Skanuj przepustkę");
            dialogStage.initModality(Modality.NONE);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);
            
            ScanPopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            dialogStage.showAndWait();
            if (controller.getIncomming() != null && controller.getIncomming().length() > 0) {
                checkIncommingData(controller.getIncomming(), null);
                
            }
        } catch (IOException e) {
            Logger.getLogger(EntryController.class
                    .getName()).log(Level.SEVERE, "[CarPark] Error during handle scan popup.", e);
        }
    }
         
    }
   

    private void checkIncommingData(String incomming, Integer id) {
        DAO dao = DaoInstanceEnum.INSTANCE.getDao();
        Integer passId;
        if (id != null) {
            ParkingspacesModel space = DaoInstanceEnum.INSTANCE.getDao().getParkingSpacesByNumber(id);
            List<ParkingpassesModel> passes = DaoInstanceEnum.INSTANCE.getDao().getParkingPassBySpaceId(space);
            ParkingpassesModel pass = passes.get(passes.size() - 1);
            passId = pass.getParkingPassId();
        } else {
            passId = PassesIdCoder.uncodeId(incomming);
        }
        if (passId != null) {
            ParkingpassesModel pass = null;
            try {
                pass = dao.getParkingPassById(passId);
                
            } catch (Throwable t) {
                Logger.getLogger(EntryController.class
                        .getName()).log(Level.SEVERE, "[CarPark] Cannot load passes from database.");
                createPopup("Błąd skanowania");
                
                return;
            }
            if (pass != null) {
                ParkingspacesModel space = pass.getNumberId();
                
                CarsModel car = pass.getCarId();
                List<PassesrecordsModel> records = new ArrayList<>(pass.getPassesrecordsModelCollection());
                if (!records.isEmpty()) {
                    client = records.get(0).getClientId();
                    this.pass = pass;
                    this.space = pass.getNumberId();
                    this.oldCar = pass.getCarId();
                    enablePassesGrid();
                }
            }
        } else {
            
            createPopupS("Złe dane");
        }
    }
    
    private void createPopupS(String text) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("popup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Uwaga");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);
            
            PopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            controller.setPopupText(text);
            dialogStage.showAndWait();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void enablePassesGrid() {
        idField.setText(pass.getParkingPassId() + "");
        stField.setText(pass.getDateIssue() + "");
        exField.setText(pass.getExpirationDate() + "");
        spField.setText(space.getNumber() + "");
        taField.setText(pass.getTarrif().getName() + "");
        caField.setText(pass.getCarId().getMake() + " " + pass.getCarId().getNumberPlate());
        PassesGrid.setVisible(true);
    }
    
    private boolean showPassTableDialog() {
      
        try {
              if(isNotNull(false)){
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("ParkingPassesTable.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Wybierz pojazd");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);
            
            controllerPass = loader.getController();
            controllerPass.setDialogStage(dialogStage);
            
            dialogStage.showAndWait();
             }
            return true;
             
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    
    private void addToDB() {
    if(isNotNull(true)){
            makeList(5);
            takeDateFromForm();
            setWrongTextFields(correctField);
            
            printValidator(correctField);
            if (isCorrect(correctField)) {
                
                List<Boolean> goodRecord = Validator.checkCarCheckList(getCar());
                setWrongTextFields(goodRecord);
                
                if (isCorrect(goodRecord)) {
                    
                    try {
                        DAO dao = DaoInstanceEnum.INSTANCE.getDao();
                        if (pass != null) {
                            CarsModel car = dao.addCar(getCar());
                            pass.setCarId(car);
                            ParkingpassesModel aPass = dao.updatePass(pass);
                            if (aPass != null) {
                                caField.setText(aPass.getCarId().getMake() + " " + aPass.getCarId().getNumberPlate());
                                createPopup("Dodano nowy pojazd!");
                            } else {
                                createPopup("Nie udało się dodać pojazdu");
                            }
                            
                            this.selectedPass = null;
                        }
                        
                        clearForm();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
       
        
    }}
    
}
